from django.conf import settings
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.generics import ListAPIView, RetrieveAPIView, CreateAPIView,UpdateAPIView
from random import randint
from django_redis import get_redis_connection
from itsdangerous import TimedJSONWebSignatureSerializer as TJS

from celery_tasks.sms_code.tasks import send_sms_code
from users.models import User

# Create your views here.

# def send_sms_code(mobile, sms_code):
#     print(111111111111)
#     ccp = CCP()
#     ccp.send_template_sms(mobile, [sms_code, '5'], 1)
from users.serializers import UserSerializers, UserShowSerializers, UserEmailSerializers


class SMS_Code_View(APIView):
    def get(self, requesst, mobile):
        # 1、获取前端传递手机号
        # 2、验证手机号格式
        # 判断前端的请求时间间隔是否在60内
        # 建立连接
        conn = get_redis_connection('sms_code')
        flag = conn.get('sme_code_flag_%s' % mobile)
        if flag:
            return Response({'error': '请求过于频繁a'}, status=403)

        # 3、生成短信验证码
        sms_code = '%06d' % randint(0, 999999)
        print(sms_code)
        pl = conn.pipeline()
        # 4、保存短信 redis string
        pl.setex('sms_code_%s' % mobile, 300, sms_code)
        # 写入一个标志数据
        pl.setex('sme_code_flag_%s' % mobile, 60, 2)
        # 将指令通过管道传递给redis
        pl.execute()
        # 5、发送短信
        # ccp = CCP()
        # ccp.send_template_sms(mobile, [sms_code, '5'], 1)
        # 线程异步执行发送短信的方法
        # t = Thread(target=send_sms_code, kwargs={'mobile': mobile, 'sms_code': sms_code})
        # t.start()

        # 使用celery
        send_sms_code.delay(mobile, sms_code)

        # 6、结果返回
        return Response('ok')


class UserNameView(APIView):
    """
        判断用户名是否重复
    """

    def get(self, request, username):
        count = User.objects.filter(username=username).count()

        return Response(
            {'count': count}
        )


class MobileView(APIView):
    """
        判断手机号是否重复
    """

    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()

        return Response(
            {'count': count}
        )


class UserView(CreateAPIView):
    """
        注册用户
    """
    serializer_class = UserSerializers


class UserShowView(RetrieveAPIView):
    """
        展示用户信息
    """

    serializer_class = UserShowSerializers

    queryset = User.objects.all()

    # 重写get——object
    def get_object(self):

        return self.request.user


class UserEmailView(UpdateAPIView):
    """
        保存更新邮箱
    """
    serializer_class = UserEmailSerializers

    # 重写get——object
    def get_object(self):
        return self.request.user


class UserEmailVifyView(APIView):
    """
        邮箱验证
    """

    def get(self,request):

        # 1、获取前端数据
        token=request.query_params.get('token')
        # 2、解密token
        tjs=TJS(settings.SECRET_KEY,300)
        try:
            data=tjs.loads(token)
        except:
            return Response({'errors':'错误的token'},status=400)
        # 3、获取解密后的用户数据
        username=data.get('username')
        # 4、根据用户名查询用户对象
        user=User.objects.get(username=username)
        # 5、更新用户的邮箱验证状态
        user.email_active=True
        user.save()
        # 6、返回验证状态
        return Response({'email_active':user.email_active})
